import { _decorator, Color, color, Component, director, find, instantiate, Label, Node, Prefab, Sprite, SpriteFrame } from 'cc';

import { ResourceManager } from '../Core/ResourceManager';
import { Core } from '../Core/Core';
import { BattleManager } from '../BattleManager';
import { EEquipmentType, EItemType, IItem, isEquipment, ItemQualityColors } from './Item';
import { Context } from '../Context';
import { EquipmentSwitchView } from './EquipmentSwitchView';
import { IEquipment } from './Equipment';
import { IGem } from './Gem';
import { EColor, EEvent, ESubView, EView } from '../Config/Enum';
import { PrefabPath } from '../Config/ResourceConfig';
import { ArsenalView } from '../Views/ArsenalView';
const { ccclass, property } = _decorator;

@ccclass('BagItem')
export class BagItem extends Component {

    //private ndItemDetail: Node;
    private itemData: IItem; // 当前物品数据
    private ndGem: Node
    ndWuxing: Node | null = null; // 五行节点
    ndWuxing_Active_1: Node | null = null; // 五行词缀1是否激活
    ndWuxing_Active_2: Node | null = null; // 五行词缀2是否激活
    ndLevel: Node | null = null; // 等级节点
    //lbPrice: boolean;
    ndPrice: Node | null = null; // 价格节点
    //ndNewEquipment: Node | null = null; // 新增的节点，用于显示新装备

    protected onLoad(): void {
        //this.ndItemDetail = find('Canvas').getChildByName("ItemDetail");
        //this.ndNewEquipment = Context.ndEquipmentSwitchView.getChildByName("Board").getChildByName("NewEquipment");

        //this.ndGem = this.node.getChildByName("Gem");

        this.ndWuxing = this.node.getChildByName("Wuxing");
        this.ndPrice = this.node.getChildByName("Price");
        this.ndWuxing_Active_1 = this.node.getChildByName("Wuxing_Active_1");
        this.ndWuxing_Active_2 = this.node.getChildByName("Wuxing_Active_2");
        this.ndLevel = this.node.getChildByName("Level");
        
    }


    protected onEnable(): void {
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        //Core.Instance.event.on(EEvent.EquipmentChanged, this.init, this);
    }

    protected start(): void {
        //this.ndItemDetail = find('Canvas').getChildByName("ItemDetail");
    }

    

    protected onDisable(): void {
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        //Core.Instance.event.off(EEvent.EquipmentChanged, this.init, this);
    }

    // 新增初始化方法
    public init(itemData: IItem) {
        console.log("设置图标BagItem init 方法被调用，itemData:", itemData);
        this.ndWuxing = this.node.getChildByName("Wuxing");
        this.ndPrice = this.node.getChildByName("Price");
        this.ndLevel = this.node.getChildByName("Level");

        //console.log("初始化 BagItem:", itemData);
        this.itemData = itemData;
        this.ndPrice.active = false;
        this.ndWuxing.active = false

        
        // 检查节点是否存在
        if (!this.node) {
            console.error("BagItem 节点不存在!");
            return;
        }
        

        if (!itemData) {
            console.log("BagItem 初始化时没有物品数据");
            //this.node.getChildByName("Icon").getComponent(Sprite).spriteFrame = null;
            this.reset();
            return;
        }

        // this.loadGem(); // 确保在初始化时加载宝石信息

        // 设置等级
        console.log("设置等级BagItem init itemData.level:", itemData.level);
        if(itemData.level===0){
            this.ndLevel.active = false
        }else{
            this.ndLevel.active = true
            this.ndLevel.getComponent(Label).string = itemData.level.toString();
        }


        
        // 设置背景颜色
        const bgNode = this.node.getChildByName("BG");
        if (bgNode) {
            const sprite = bgNode.getComponent(Sprite);
            if (sprite) {
                sprite.color = color().fromHEX(ItemQualityColors[itemData.quality]);
            } else {
                console.warn("BG 节点上没有 Sprite 组件");
            }
        } else {
            console.warn("找不到 BG 节点");
        }
        
        // 设置图标
        const iconNode = this.node.getChildByName("Icon");
        console.log("设置图标itemData.nameBagItem init iconNode:", iconNode,itemData.name);
        if (iconNode) {
            const sprite = iconNode.getComponent(Sprite);
            console.log("设置图标BagItem init iconNode sprite:", sprite,itemData.name);
            if (sprite) {
                console.log("设置图标:", itemData.icon, itemData.name);
                // const spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(itemData.icon);
                // if (spriteFrame) {
                //     sprite.spriteFrame = spriteFrame;
                // } else {
                //     console.warn("未能加载图标:", itemData.icon);
                // }
                ResourceManager.Instance.loadRes<SpriteFrame>(itemData.icon+"/spriteFrame").then((spriteFrame) => {
                    sprite.spriteFrame = spriteFrame;

                    console.log("aaaaaaaaaaaaaa1itemData.icon+spriteFrame", itemData.icon+"/spriteFrame");
                    console.log("aaaaaaaaaaaaaa1", spriteFrame);
                }).catch((error) => {
                    console.error("加载图标失败:", error);
                });
            } else {
                console.warn("Icon 节点上没有 Sprite 组件");
            }
        } else {
            console.warn("找不到 Icon 节点");
        }

        // 设置数量
        const lbCountNode = this.node.getChildByName("LB_Count");
        if (lbCountNode) {
            const label = lbCountNode.getComponent(Label);
            if (label) {
                if (itemData.stackable && itemData.count && itemData.count > 1) {
                    label.string = itemData.count.toString();
                    lbCountNode.active = true;
                }
                else {
                    lbCountNode.active = false;
                }
            } else {
                console.warn("LB_Count 节点上没有 Label 组件");
            }
        } else {
            console.warn("找不到 LB_Count 节点");
        }

        // 如果是装备，设置五行icon颜色
        
        if (isEquipment(itemData)) {
            console.log("是装备，设置五行icon颜色itemData:", itemData);
            this.ndWuxing.active = true
            //const equipment = itemData;
            if (this.ndWuxing) {
                const sprite = this.ndWuxing.getComponent(Sprite);
                if (sprite) {
                    console.log("设置五行颜色:", itemData.wuxing);
                    sprite.color = color().fromHEX(EColor[itemData.wuxing]);
                } else {
                    console.warn("Wuxing 节点上没有 Sprite 组件");
                }
            }
        }


        // 如果当前是商店界面，显示价格
        if (Core.Instance.currentSubView === ESubView.Shop) {
            console.log("当前是商店界面，显示价格itemData:", itemData);
            this.ndPrice.active = true
            this.loadPrice()
            
        }

        // 如果当前是PlayerView，检查五行是否激活，如果激活则显示Wuxing_Active_1和Wuxing_Active_2
        // console.log("检查五行激活BagItem init Core.Instance.currentView:", Core.Instance.currentView);  
        // console.log("检查五行激活BagItem init isEquipment(this.itemData):", isEquipment(this.itemData));
        // console.log("检查五行激活BagItem init Core.Instance.currentSubView",Core.Instance.currentSubView);
        // if (isEquipment(this.itemData) && Core.Instance.currentView === EView.PlayerView && Core.Instance.currentSubView !== ESubView.EquipmentSwitch) {
        //     console.log("检查五行激活当前是PlayerView，检查五行是否激活，如果激活则显示Wuxing_Active_1和Wuxing_Active_2itemData:", itemData);
        //     this.loadWuxingActive(this.itemData)
        // }
        if (isEquipment(this.itemData) && Core.Instance.currentView === EView.PlayerView ){
            this.loadWuxingActive(this.itemData)
        }


    }

    private onTouchEnd() {
        console.log("点击了BagItem:", this.itemData);
        if (!this.itemData && Core.Instance.currentView === EView.PlayerView) {
            // 打开装备切换界面
            Core.Instance.currentEquipmentType = this.node.name as EEquipmentType;
            console.log("没有物品数据，打开装备切换界面");
            this.showEquipmentSwitchView();
            return
            //Context.ndEquipmentSwitchView.active = true;
        } else if (!this.itemData && Core.Instance.currentView === EView.ArsenalView) {
            return 
        }
        if(this.node.parent.parent.name === "ItemDetail"){return}

        if (this.node.parent.name === "CurrentEquipment" || this.node.parent.name === "NewEquipment" || this.node.parent.name === "ItemDetail" ) {return; } 
        if (this.node.parent.parent.parent.parent.name === "EquipmentSwitchView") {return} // 如果在装备切换界面，把点击装备放在NewEquipment
        if (this.node.parent.parent.parent.parent.name  === "Bag_EquipmentSwitch") {
            console.log("this.node.parent.parent.parent.parent.parent.name=EquipmentSwitchView:", this.itemData);
            Context.ndEquipmentSwitchView.getComponent(EquipmentSwitchView).loadNewEquipment(this.node.name);
            return;
        }
        if (Core.Instance.currentSubView === ESubView.Forge) {
            console.log("BagItem 点击事件 在锻造界面:", this.itemData);
            Core.Instance.currentItem = this.itemData;
            Context.ndArsenalView.getComponent(ArsenalView).onButtonLoadItemToForge();
            return;
        }


        //Context.ndEquipmentSwitchView.getComponent(EquipmentSwitchView).loadNewEquipment();
        
        //if (this.node.parent.name === "CurrentEquipment") {return; } // 如果在当前装备界面，不处理点击事件

        console.log("点击了BagItem 走默认逻辑 展示ItemDetail:", this.itemData);
        Core.Instance.currentEquipmentType = this.node.name as EEquipmentType;
        Core.Instance.currentItem = this.itemData;
        // 显示物品详情
        this.showItemDetail();
    }

        // 在 BagItem 类中添加方法
    // private isEquipment(item: IItem): item is IEquipment {
    //     return item.itemType === EItemType.Equipment;
    // }

    private isGem(item: IItem): item is IGem {
        return item.itemType === EItemType.Gem;
    }


    loadGem() {
        if (!this.itemData) return;
        
        if (isEquipment(this.itemData)) {
            //console.log("11111BagItem loadGem this.itemData 是 IEquipment:", this.itemData);
            // 现在 TypeScript 知道 this.itemData 是 IEquipment
            const equipment = this.itemData;
            //console.log("11111BagItem装备的宝石插槽数:", equipment.gemSlots);
            
            // 可以安全访问 equipment.gemSlots
            if (this.ndGem) {
                this.ndGem.active = equipment.gemSlots > 0;
                switch (equipment.gemSlots) {
                    case 0:
                        this.ndGem.active = false;
                        console.log("11111BagItem装备没有宝石插槽");
                        break;
                    case 1:
                        this.ndGem.getChildByName("Gem1").active = true;
                        this.ndGem.getChildByName("Gem2").active = false;
                        this.ndGem.getChildByName("Gem3").active = false;
                        console.log("11111BagItem装备有1个宝石插槽");
                        break;
                    case 2:
                        this.ndGem.getChildByName("Gem1").active = true;
                        this.ndGem.getChildByName("Gem2").active = true;
                        this.ndGem.getChildByName("Gem3").active = false;
                        console.log("11111BagItem装备有2个宝石插槽");
                        break;
                    case 3:
                        this.ndGem.getChildByName("Gem1").active = true;
                        this.ndGem.getChildByName("Gem2").active = true;
                        this.ndGem.getChildByName("Gem3").active = true;
                        break;
                    default:
                        console.warn(`装备 ${equipment.name} 的宝石插槽数异常: ${equipment.gemSlots}`);
                        this.ndGem.active = false;
                        break;
                }
                
                // const gemLabel = this.ndGem.getComponent(Label);
                // if (gemLabel && equipment.gemSlots > 0) {
                //     gemLabel.string = `${equipment.gemSlots}`;
                // }
            }
        }
    }


    showItemDetail() {
        
        if (!this.itemData) {
            // 实例化EquipmentSwitchView prefab
                    // 获取BagItem预制体
        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.EquipmentSwitchView) as Prefab;
        console.log("ItemDetail预制体:", prefab);

        const EquipmentSwitchViewNode = instantiate(prefab);
        Context.ndEquipmentSwitchView = EquipmentSwitchViewNode;


        EquipmentSwitchViewNode.setParent(find("Canvas") as Node);
            return;
        };

        //if (this.isEquipment(this.itemData)) {
            // 实例化ItemDetail prefab

            // 获取BagItem预制体
            const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.ItemDetail) as Prefab;
            console.log("ItemDetail预制体:", prefab);

            const ItemDetailNode = instantiate(prefab);

            ItemDetailNode.setParent(find("Canvas") as Node);



        //}

    }

    showEquipmentSwitchView() {
        
        // 获取EquipmentSwitchView预制体
        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.EquipmentSwitchView) as Prefab;
        console.log("ItemDetail预制体:", prefab);

        const EquipmentSwitchViewNode = instantiate(prefab);

        EquipmentSwitchViewNode.setParent(find("Canvas") as Node);
        EquipmentSwitchViewNode.active = true;
        Context.ndEquipmentSwitchView = EquipmentSwitchViewNode;
    }




    //     onButtonShowDetail() {
    //     if(this.node.parent.parent.name === "EquipmentDetail"){return}
        
    //     Core.Instance.currentEquipmentType = this.node.name;
    //     console.log("点击了物品", this.node.name);
    //     console.log("Core.Instance.currentEquipmentType:", Core.Instance.currentEquipmentType);
    //     // 如果没有装备则return
    //     if (!Core.Instance.players.get(Core.Instance.currentPlayer).equipmentData.equipped.has(Core.Instance.currentEquipmentType)) {
    //         //console.error("当前玩家没有装备:", Core.Instance.currentEquipmentType);
    //         Context.ndEquipmentSwitchView.active = true;
    //         return;
            
    //     }



    //     // 显示EquipmentDetail节点
    //     this.ndEquipmentDetail.active = true;


    // }

    // 恢复默认的空item状态
    reset(){
        this.node.getChildByName("Icon").getComponent(Sprite).spriteFrame = null;
        this.node.getChildByName("BG").getComponent(Sprite).color = Color.WHITE;
        this.ndWuxing.getComponent(Sprite).color = Color.WHITE;
        this.ndWuxing_Active_1.active = false;
        this.ndWuxing_Active_2.active = false
        this.ndLevel.active = false;


    }

    loadPrice(){
        console.log("ShopItem loadPrice:", this.itemData);
        if (!this.itemData) return;
        if ((this.itemData as any).price !== undefined) {

            this.ndPrice.active = true; // 显示价格节点
            this.ndPrice.getComponent(Label).string = `${(this.itemData as any).price} `;
        }

    }

    loadWuxingActive(itemData: IEquipment){
        console.log("BagItem loadWuxingActive:(this.itemData as any).affixes_wuxing[0]",(this.itemData as any).affixes_wuxing[0]);
        if(itemData.affixes_wuxing[0]){
            if (itemData.affixes_wuxing[0].isActive) {
                this.ndWuxing_Active_1.active = true;
            }else{
                this.ndWuxing_Active_1.active = false;
            }
        }
        if(itemData.affixes_wuxing[1]){
            if (itemData.affixes_wuxing[1].isActive) {
                this.ndWuxing_Active_2.active = true;
            }else{
                this.ndWuxing_Active_2.active = false;
            }
        }
}


}